package com.xjl.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xjl.demo.Admin;
import com.xjl.service.AdminService;
import com.xjl.service.impl.AdminServiceImpl;
/**
 * 处理用户登录
 * @author JianLin_Xu
 *
 */


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	
	AdminService ad = new AdminServiceImpl();
	
	protected void service(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;utf-8");
		//处理请求信息
		if(req.getParameter("adminid")!=null && req.getParameter("adminpwd")!=null ){
			int  adminid = Integer.parseInt(req.getParameter("adminid"));
			String adminpwd = req.getParameter("adminpwd");
			//进行登陆校验
		
			try{
				
				Admin admin = ad.CheckAdminLoginService(adminid, adminpwd);
				if(admin!=null){
					//用户ID密码正确，重定向到index.jsp
					HttpSession hs=req.getSession();
					//将用户数据存储到session中
			//		hs.setAttribute("adminname", admin.getAdminname());
			//		System.out.println(admin.getAdminname());
					hs.setAttribute("admin", admin);
					resp.sendRedirect("admin/index.jsp");
					return;
				}else{
					//System.out.println("登录失败");
					//用户名密码错误，请求转发到index.jsp
					//添加标识符到request中
					req.setAttribute("error","账号密码不正确。请重新输入");
					//请求转发
					req.getRequestDispatcher("admin/login.jsp").forward(req, resp);
					return;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}else{
			req.getRequestDispatcher("admin/login.jsp").forward(req, resp);
		}
			
	}

}
